const Favorite = require('../models/Favorite');

// 添加收藏
const addFavorite = async (req, res) => {
  try {
    const userId = req.user.userId;
    const { carId } = req.body;

    if (!carId) {
      return res.status(400).json({ message: '车辆ID不能为空' });
    }

    await Favorite.add(userId, carId);

    res.json({ message: '收藏成功' });
  } catch (error) {
    if (error.message === '该车辆已在收藏列表中') {
      return res.status(400).json({ message: error.message });
    }
    console.error('添加收藏错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 移除收藏
const removeFavorite = async (req, res) => {
  try {
    const userId = req.user.userId;
    const { carId } = req.params;

    const success = await Favorite.remove(userId, carId);
    if (!success) {
      return res.status(404).json({ message: '收藏记录不存在' });
    }

    res.json({ message: '取消收藏成功' });
  } catch (error) {
    console.error('移除收藏错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 获取收藏列表
const getFavorites = async (req, res) => {
  try {
    const userId = req.user.userId;

    const favorites = await Favorite.findByUser(userId);

    res.json({ favorites });
  } catch (error) {
    console.error('获取收藏列表错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 检查是否已收藏
const checkFavorite = async (req, res) => {
  try {
    const userId = req.user.userId;
    const { carId } = req.params;

    const exists = await Favorite.exists(userId, carId);

    res.json({ isFavorite: exists });
  } catch (error) {
    console.error('检查收藏错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

module.exports = {
  addFavorite,
  removeFavorite,
  getFavorites,
  checkFavorite
};